package com.cncytech.uiautomator_demo.utils;

import android.os.Environment;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import jxl.Cell;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class ExcelUtil {

    WritableWorkbook workbook = null;
    WritableSheet sheet = null;
    String[] title = new String[]{"编号", "测试标题", "测试说明", "测试结果"};
    File file;

    public ExcelUtil() {
        init(null);
    }

    public ExcelUtil(String fileName, String... title) {
        this.title = title;
        init(fileName, title);
    }

    public void init(String fileName, String... title) {
        if (Objects.isNull(fileName)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
            fileName = sdf.format(new Date());
        }
        file = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + fileName);

        try {
            file.createNewFile();
            workbook = Workbook.createWorkbook(file);
            sheet = workbook.createSheet("测试结果", 0);

            for (int i = 0; i < title.length; i++) {
                sheet.addCell(new Label(i, 0, title[i]));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void write() {
        int columns = sheet.getColumns();
        Cell[] row = sheet.getRow(0);
        for (Cell cell : row) {
            if ("测试标题".equals(cell.getContents())) {
                System.out.println(cell.getColumn());
            }
        }
    }

    public void writeData(List<Map<String, Object>> datas) {
        try {
            Label label;
            // todo 每行的数据
            for (int row = 0; row < datas.size(); row++) {
                Map<String, Object> stringObjectMap = datas.get(row);
                Set<String> keys = stringObjectMap.keySet();

                for (int column = 0; column < keys.size(); column++) {
                    label = new Label(column, row, stringObjectMap.get("") == null ? "" : String.valueOf(stringObjectMap.get("")));
                    sheet.addCell(label);
                }
            }
            workbook.write();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                workbook.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void writeRow(Map<String, Object> data, int row) {
        data.forEach((k, v) -> {
            int c = 0;
            new Label(c++, row, String.valueOf(v));
        });
    }


    public int getCurrentRows() {
        return sheet.getRows();
    }
}
